package tomoto.util;

/**
 * Helper utilities to operate numbers.
 * 
 * @author Tomoto Shimizu Washio
 * 
 */
public class NumberUtil {
	/**
	 * Parses a string by {@link Integer#parseInt(String)} and returns the
	 * result, or returns the specified default value in case of error.
	 * 
	 * @param value string to parse
	 * @param defaultValue default value returned in case of error
	 * @return as described above
	 */
	public static int parseIntWithDefault(String value, int defaultValue) {
		try {
			return Integer.parseInt(value);
		} catch (NumberFormatException ex) {
			return defaultValue;
		}
	}

	/**
	 * Parses a string by {@link Integer#parseInt(String, int)} and returns the
	 * result, or returns the specified default value in case of error.
	 * 
	 * @param value string to parse
	 * @param radix
	 * @param defaultValue default value returned in case of error
	 * @return as described above
	 */
	public static int parseIntWithDefault(String value, int radix, int defaultValue) {
		try {
			return Integer.parseInt(value, radix);
		} catch (NumberFormatException ex) {
			return defaultValue;
		}
	}

	/**
	 * Counts the number of bits set in an int value.
	 * 
	 * @param value int value to count bits
	 * @return number of set bits
	 */
	public static int countBits(int value) {
		int bits = 0;
		while (value != 0) {
			if ((value & 1) != 0) {
				bits++;
			}
			value >>>= 1;
		}
		return bits;
	}

}
